﻿using System;
using System.Diagnostics;
using System.ServiceModel;
using ShellCommandsClientService.PushShellCommandServiceReference;
using ShellCommandsClientService.ShellCommandResultServiceReference;

namespace ShellCommandsClientService
{
    class MyCallBack : IPushShellCommandCallback, IDisposable
    {
        private PushShellCommandClient proxy;
        private ShellCommandExecResultClient loggerProxyClient;
        public void CallBackFunction(ShellCommandInfo shellCommandInfo)
        {
            Process cmd = new Process();
            string result = string.Empty;
            bool isShellCommnadRunSuccess = false;
            try
            {
                cmd.StartInfo.FileName = "cmd.exe";
                cmd.StartInfo.RedirectStandardInput = true;
                cmd.StartInfo.RedirectStandardOutput = true;
                cmd.StartInfo.CreateNoWindow = true;
                cmd.StartInfo.UseShellExecute = false;

                cmd.Start();

                /* execute "dir" */

                cmd.StandardInput.WriteLine(shellCommandInfo.Text);
                cmd.StandardInput.Flush();
                cmd.StandardInput.Close();
                
                result = cmd.StandardOutput.ReadToEnd();
                isShellCommnadRunSuccess = true;
            }
            catch (Exception ex)
            {
                result = ex.Message + " " + ex.Source;
            }
            if (loggerProxyClient == null)
            {
                loggerProxyClient = new ShellCommandExecResultClient();
            }
            ShellCommandResult shellCommandResult = new ShellCommandResult()
            {
                MachineName = shellCommandInfo.MachineName,
                Result = result,
                ExecutionTime = DateTime.Now,
                Command = shellCommandInfo.Text
            };
            if (isShellCommnadRunSuccess)
            {
                shellCommandResult.Type = ResultType.Success;
            }
            else
            {
                shellCommandResult.Type = ResultType.Exception;
            }
            loggerProxyClient.LogResult(shellCommandResult);
        }

        public void callService()
        {
            InstanceContext context = new InstanceContext(this);
            proxy = new PushShellCommandClient(context);
            proxy.NormalFunction(System.Environment.MachineName);
        }

        public void Dispose()
        {
            proxy.Close();
        }

    }
}
